package com.sixbro.data.redis.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * <p>
 *  Redis主题监听器
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021-12-20 10:27
 */
@Slf4j
@Configuration
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 接收主题消息
     *
     * @param message 接收到的消息
     * @param pattern 订阅的主题
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("过期监听事件启动");

        String topic = new String(pattern);
        String body = new String(message.getBody());
        System.out.println("订阅的主题是:" + topic);
        System.out.println("接收到的消息:" + body);
    }
}
